package com.gome.ss.webserver.servlet.api;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gome.ss.flowcrawl.extractor.FlowCrawlExtractor;
import com.gome.ss.flowcrawl.extractor.FlowCrawlExtractorManager;
import com.mongodb.BasicDBObject;

public class FlowCrawlExtractCtrl extends HttpServlet {
	
	/* /spiderkit/flowcrawl_add */
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String action = req.getParameter("action");
		String pluginName = req.getParameter("pluginName");
		String stepID = req.getParameter("stepID");
		String taskTypeString = req.getParameter("taskType");
		int taskType = -1;
		if (taskTypeString != null)
			taskType = Integer.valueOf(taskTypeString);
		
		resp.setContentType("text/html;charset=gbk");
		req.setCharacterEncoding("gbk");
		
		if (pluginName != null && !pluginName.isEmpty()) {
			if (action.equals("start")) {
				int ret = FlowCrawlExtractorManager.getInstance().start(pluginName, stepID, taskType);
				resp.getWriter().print(String.valueOf(ret));
				resp.getWriter().close();
			} else if (action.equals("stop")) {
				FlowCrawlExtractorManager.getInstance().stop(pluginName, stepID);
				resp.getWriter().print("0");
				resp.getWriter().close();
			} else if (action.equals("test")) {
				FlowCrawlExtractor extractor = FlowCrawlExtractorManager.getInstance().buildForRandomExtractor(pluginName, stepID);
				if (extractor != null) {
					BasicDBObject obj = new BasicDBObject();
					BasicDBObject dataObj = extractor.getRandomOne();
					if (dataObj == null) {
						obj.append("status", "-1");
						obj.append("message", "No data!");
					} else {
						obj.append("status", "1");
						obj.append("data", dataObj);
					}
					resp.getWriter().print(obj.toString());
				}
				
				resp.getWriter().close();
			}
		}

		resp.getWriter().print("");
		resp.getWriter().close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(req, resp);
	}

}
